import datetime
import os
import sys
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from webdriver_manager.microsoft import EdgeChromiumDriverManager


class Driver:
    def __init__(self):
        options = webdriver.EdgeOptions()
        self.driver = webdriver.Edge(
            service=EdgeService(EdgeChromiumDriverManager().install()),
            options=options
        )

    def getScreenShot(self):
        """保存当前页面截图到按日期分类的目录中"""
        # 生成日期目录
        date_dir = datetime.datetime.now().strftime('%Y-%m-%d')
        save_dir = os.path.join("../images", date_dir)

        try:
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
        except PermissionError as e:
            print(f"目录创建失败：{e}")
            return

        # 生成文件名：调用者函数名 + 时间戳
        caller_name = sys._getframe().f_back.f_code.co_name
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S')
        filename = f"{caller_name}-{timestamp}.png"

        # 保存截图
        save_path = os.path.join(save_dir, filename)
        try:
            self.driver.save_screenshot(save_path)
            print(f"截图已保存至：{save_path}")
        except Exception as e:
            print(f"截图保存失败：{e}")


# 使用示例
if __name__ == "__main__":
    blog_driver = Driver()
    blog_driver.driver.get("https://www.baidu.com")  # 先打开网页
    blog_driver.getScreenShot()
    blog_driver.driver.quit()  # 关闭浏览器